package com.fpd.tools;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 导出工具类
 * @author zhengzhibiao
 * @date 2019-11-02 16:11
 */
public class ExportUtil {

    private static final Logger logger = LoggerFactory.getLogger(ExportUtil.class);


    /**
     * 导出Excel
     * @param excelName 文件名
     * @param dataList 导出的数据
     * @param response response
     */
    public static void exportExcel(String excelName, List<? extends Object> dataList, HttpServletResponse response) {
        if (StringUtils.isBlank(excelName)) {
            excelName = "";
        }
        try {
            String fileName = excelName + "_" + System.currentTimeMillis() + ".xls";
            HSSFWorkbook wb = ExcelUtil.getSimpleHSSFWorkbook(excelName, dataList);
//            fileName = new String(fileName.getBytes(),"ISO8859-1");
            fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
//            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

            ServletOutputStream out = response.getOutputStream();
            try {
                wb.write(out);
                out.flush();
            } catch (Exception e) {
                logger.error("导出Excel-文件写入异常：{}", e.getMessage());
            } finally {
                out.close();
            }
        } catch (Exception e) {
            logger.error("导出Excel异常：{}", e.getMessage());
        }
    }

    /**
     * easypoi 导出
     */
    public static void exportExcel(String excelName, Workbook workBook, HttpServletResponse response) {
        if (StringUtils.isBlank(excelName)) {
            excelName = "";
        }
        try {
            String fileName = excelName + "_" + System.currentTimeMillis() + ".xls";
//            fileName = new String(fileName.getBytes(),"ISO8859-1");
            fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
//            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            ServletOutputStream out = response.getOutputStream();
            try {
                workBook.write(out);
                out.flush();
            } catch (Exception e) {
                logger.error("导出Excel-文件写入异常：{}", e.getMessage());
            } finally {
                out.close();
            }
        } catch (Exception e) {
            logger.error("导出Excel异常：{}", e.getMessage());
        }
    }



}
